package com.qsdjf.fp.weixin.task;

import java.io.IOException;
import java.util.Map;
import java.util.TimerTask;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qsdjf.fp.weixin.cache.TokenCache;
import com.qsdjf.fp.weixin.configuration.properties.Config;

@Repository
public class TokenTask extends TimerTask {
	private Logger logger = LoggerFactory.getLogger(TokenTask.class);
	@Autowired
	private Config config;

	public void freshToken() {
		try {
			// 获取accesstoken
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
					+ config.getAppid() + "&secret=" + config.getAppsecret());
			CloseableHttpResponse response;

			response = httpclient.execute(httpGet);

			String responseStr = EntityUtils.toString(response.getEntity());
			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, String> accessMap = objectMapper.readValue(responseStr,
					new TypeReference<Map<String, String>>() {
					});
			TokenCache.setAccessToken(accessMap.get("access_token"));
			TokenCache.setExpiresIn(Long.valueOf(accessMap.get("expires_in")));

			// 获取jsapiTicket
			httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
					+ TokenCache.getAccessToken() + "&type=jsapi");
			response = httpclient.execute(httpGet);
			responseStr = EntityUtils.toString(response.getEntity());
			accessMap = objectMapper.readValue(responseStr, new TypeReference<Map<String, String>>() {
			});
			TokenCache.setJsapiTicket(accessMap.get("ticket"));
			long temp = Long.valueOf(Long.valueOf(accessMap.get("expires_in")));
			TokenCache.setExpiresIn(TokenCache.getExpiresIn() < temp ? TokenCache.getExpiresIn() : temp);
		} catch (IOException e) {
			logger.error("刷新token失败", e);
		}
	}

	@Override
	public void run() {
		freshToken();
	}
}
